<template>
  <div class="favorite-view">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2 class="page-title">
          <el-icon>
            <Star />
          </el-icon>
          <span>我的收藏</span>
        </h2>
        <p class="page-subtitle">共收藏了 <span>{{ total }}</span> 篇文章</p>
      </div>

      <!-- 收藏列表 -->
      <div class="favorite-list" v-loading="loading">
        <div v-if="favorites.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无收藏，快去收藏喜欢的文章吧~">
            <el-button type="primary" @click="goToDiscover">去发现</el-button>
          </el-empty>
        </div>
        <ListItem v-else :arr="favorites" />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination v-model:current-page="pageNum" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handlePageChange" background />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star } from '@element-plus/icons-vue'
import ListItem from '@/components/ListItem.vue'
import { getUserFavorites, host, removeFavorite } from '@/api/index'

const router = useRouter()

interface IFavorite {
  id: number
  article_id: number
  title: string
  author: string
  content: string
  createAt: string
  src: string
  tag: string
  cate: string
  [key: string]: any
}

const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(15)
const total = ref(0)
const favorites = ref<IFavorite[]>([])

// 获取收藏列表
const loadFavorites = async () => {
  loading.value = true
  try {
    const resData = await getUserFavorites({
      page_num: pageNum.value,
      page_size: pageSize.value
    })
    if (resData && resData.code === 200) {
      favorites.value = (resData.data || []).map((item: any) => {
        // 映射数据格式，适配ListItem组件
        const mappedItem: IFavorite = {
          id: item.article_id || item.id,  // 使用文章ID
          article_id: item.article_id,
          title: item.title || '',
          author: item.author || '',
          content: item.content || '',
          createAt: item.article_createAt || item.createAt || '',  // 使用文章创建时间
          src: item.src || '',
          tag: item.tag || '',
          cate: item.cate || '',
          view_count: item.view_count || 0
        }
        // 处理图片URL
        if (mappedItem.src && !mappedItem.src.startsWith('http')) {
          mappedItem.src = host + (mappedItem.src.startsWith('/') ? mappedItem.src : '/' + mappedItem.src)
        }
        // 处理日期
        if (mappedItem.createAt) {
          const date = new Date(mappedItem.createAt)
          mappedItem.createAt = date.toISOString()
        }
        return mappedItem
      })
      total.value = resData.total || 0
    } else {
      ElMessage.error(resData?.msg || '获取收藏列表失败')
    }
  } catch (error: any) {
    console.error('获取收藏列表失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.error('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('获取收藏列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 分页变化处理
const handlePageChange = (page: number) => {
  pageNum.value = page
  loadFavorites()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 跳转到发现页
const goToDiscover = () => {
  router.push('/discover')
}

onMounted(() => {
  loadFavorites()
})
</script>

<style lang="less" scoped>
@import "../assets/varable.less";

.favorite-view {
  min-height: calc(100vh - 300px);
  padding: 40px 0;

  .page-header {
    margin-bottom: 30px;
    text-align: center;

    .page-title {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;
      font-size: 32px;
      font-weight: 600;
      color: @text-primary;
      margin: 0 0 10px 0;

      .el-icon {
        font-size: 36px;
        color: @primary-color;
      }
    }

    .page-subtitle {
      color: @text-secondary;
      font-size: 16px;
      margin: 0;

      span {
        color: @primary-color;
        font-weight: 600;
      }
    }
  }

  .favorite-list {
    min-height: 400px;
  }

  .empty-state {
    padding: 60px 0;
    text-align: center;
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 40px;
    padding: 20px 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .favorite-view {
    padding: 20px 0;

    .page-header {
      margin-bottom: 20px;

      .page-title {
        font-size: 24px;

        .el-icon {
          font-size: 28px;
        }
      }

      .page-subtitle {
        font-size: 14px;
      }
    }
  }
}
</style>
